#define NOMINMAX
#include "TreasuryFutures.h"
#include <core/StyleMgr.h>
#include <core/ImageMgr.h>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QLabel>
#include "TreasuryFuturesList.h"
#include "TreasuryFuturesChart.h"
#include "../StringResource.h"
#include <tfbondlib/tfBondDataCenter.h>

TreasuryFutures::TreasuryFutures(QWidget* p)
	: SDialog(p),
	  m_TFDataHandler(nullptr)
{
	setTitle(NewStringTable::strFixedIncomeTitle(0));

	QVBoxLayout* layout = qobject_cast<QVBoxLayout*>(this->layout());
	if (!layout)return;
	layout->setSpacing(10);
	m_list = new TreasuryFuturesList(this, &m_data);
	layout->addWidget(m_list);
	layout->setStretch(1, 5);
	m_chart = new TreasuryFuturesChart(this, &m_data);
	layout->addWidget(m_chart);
	layout->setStretch(2, 5);

	m_TFDataHandler = new FixedNatFutureHandler(&m_data);
	connect(m_TFDataHandler, &FixedNatFutureHandler::recvData, this, &TreasuryFutures::onDataResponse);
	connect(&TFBondDataCenter::instance(), &TFBondDataCenter::recvData, this, &TreasuryFutures::onDataResponse);
	connect(m_list, &TreasuryFuturesList::clickedRow, this, &TreasuryFutures::onClickedTFListRow);
	connect(&getCTDInfo(), &CQuoteBoardLoadCTDInfo::ctdChanged, this, &TreasuryFutures::onCTDChanged);
	reloadData();

	startTimer(50);
}

TreasuryFutures::~TreasuryFutures()
{
	if (m_TFDataHandler) {
		delete m_TFDataHandler;
		m_TFDataHandler = nullptr;
	}
}

SDialog* TreasuryFutures::clone(QWidget* parent)
{
	return new TreasuryFutures(parent);
}


void TreasuryFutures::timerEvent(QTimerEvent* event)
{
	if (!m_dataDirty)
		return;

	m_list->onRefresh();
	m_dataDirty = false;
}

void TreasuryFutures::onDataResponse(int funcId)
{
	switch (funcId) {
	case E_FID_QB_TF_CONTACT_INFO_REQ:
		reloadData();
		break;
	case E_FID_QB_TF_PRICE_REQ_V2:
	case E_FID_QB_TF_PRICE_PUSH_V3:
		refreshTFList();
		break;
	case E_FID_QB_TF_REALTIME:
		refreshTFChart();
		break;
	case E_FID_QB_MARKET_STREAM_DEAL_REQ:
	case E_FID_QB_MARKET_STREAM_DEAL_PUSH:
		refreshTFList();
		break;
	default:
		break;
	}
}

void TreasuryFutures::reloadData()
{
	if (m_TFDataHandler){
		m_TFDataHandler->cancelReqTFPrice();
		m_TFDataHandler->clearData();
		m_TFDataHandler->reqTFPrice();
	}
}

void TreasuryFutures::refreshTFList() {
	m_dataDirty = true;
}

void TreasuryFutures::refreshTFChart() {
	m_chart->onRefresh();
}

void TreasuryFutures::onClickedTFListRow(const QString& TFId) {
	if (m_TFDataHandler) {
		m_data.SetCurrentTFID(TFId);
		m_TFDataHandler->reqRealtimeData(TFId);
	}
}

void TreasuryFutures::onCTDChanged() {
	refreshTFList();
}
